<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" id="btnFile" />
    <button onclick="upload()">上传</button>
    <button id="btnMerge">合并</button>
  </body>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.js"></script>
  <script>
    const btnFile = document.getElementById("btnFile");
    let ajax = axios.create({
      baseURL: "http://localhost:3000",
    });
    ajax.interceptors.request.use((config) => {
      return config;
    });
    ajax.interceptors.response.use((response) => {
      return response.data;
    });

    ajax.get("/cs").then((res) => console.log(res));
    let chunkSize = 1024 * 1024; // 1MB
    let index = 0;
    var fileName;
    btnFile.onchange = function (event) {
      ajax.defaults.headers["Content-type"] =
        "application/x-www-form-urlencoded";
      let file = event.target.files[0];
      fileName = file.name;
      console.log(file, "file");
      let [fname, fext] = file.name.split(".");
      chunkSize = Math.floor(file.size / 5);
      let blob;

      for (let i = 0; i < 5; i++) {
        if (i == 4) {
          blob = file.slice(index); //Blob
          console.log(blob, Object.prototype.toString.call(blob));
        } else {
          blob = file.slice(index, chunkSize * (i + 1));
        }

        index = chunkSize * (i + 1);
        let blobName = `${fname}.${i}.${fext}`;

        let blobFile = new File([blob], blobName);

        let formData = new FormData();
        formData.append("file", blobFile);

        ajax.post("/upload", formData).then((res) => {
          console.log(res);
        });
      }
    };
    btnMerge.onclick = function () {
      ajax.defaults.headers["Content-type"] = "application/json";
      ajax({
        method: "post",
        url: "http://localhost:3000/merge",
        data: { name: fileName },
      }).then((res) => console.log(res));
    };
  </script>
</html>
